<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Tool\SendEmailTools;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class UsersController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
        $users = User::all();
        return view('users.index',compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('users.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            "name" => ['required','max:200',Rule::unique('users')],
            "email" => ['required','email',Rule::unique('users')],
            "password" => ['required','min:6','confirmed'],
        ],\Lang::get('validate'),\Lang::get('validate.attributes'));


        $request['password'] = bcrypt($request['password']);

        $user = User::create(\request()->all());

        $sendEmailTools = new SendEmailTools();
        $sendEmailTools->sendMail($user);

        session()->flash('warning','注册成功,还需前往邮箱激活');
        return redirect()->route('login');

    }

    /**
     * Display the specified resource.
     */
    public function show(User $user)
    {
        //
        $posts = $user->posts()->paginate(10);
        return view('users.show',compact('user','posts'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(User $user)
    {
        return view('users.edit',compact('user'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, User $user)
    {
        $this->validate($request,[
            "name" => ['required','max:200'],
            "password" => ['nullable','min:6','confirmed'],
        ],\Lang::get('validate'),\Lang::get('validate.attributes'));


        $data = [];
        if ($request->password) {
            $data['password'] = bcrypt($request->password);
        }
        $data['name'] = $request->name;
        $user->update($data);
        session()->flash('success','修改成功');
        return redirect()->route('users.show',$user);

    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
